/**
 *
 */

package lohmar.ashar.android.util;

import android.content.ContextWrapper;
import android.content.SharedPreferences.Editor;
import android.util.AndroidRuntimeException;

import java.util.Map;

/**
 * @author Mihai HARAS (Lohmar ASHAR) 2011
 */
public abstract class APreferenceAware<T> {

    public void deleteValue(String key) {
        Editor editor = getContext().getSharedPreferences(getPrefName(), 0).edit();
        editor.remove(key);
        editor.commit();
    }

    @SuppressWarnings("unchecked")
    public T getValue(String key) {
        Map<String, ?> prefs = getContext().getSharedPreferences(getPrefName(), 0).getAll();
        if (prefs.containsKey(key)) {
            try {
                return (T) prefs.get(key);
            } catch (ClassCastException e) {
                throw new AndroidRuntimeException();
            }
        }
        return null;

    }

    public void setValue(String key, T value) {
        Editor editor = getContext().getSharedPreferences(getPrefName(), 0).edit();
        if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof Long) {
            editor.putLong(key, (Long) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value);
        } else if (value instanceof String) {
            editor.putString(key, (String) value);
        } else
            throw new AndroidRuntimeException("Type " + value.getClass().getName() + " not supported ");
        editor.commit();
    }

    protected abstract ContextWrapper getContext();

    protected abstract String getPrefName();
}
